package com.yanxibao.service.impl;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yanxibao.bean.History;
import com.yanxibao.common.Result;
import com.yanxibao.dto.PageQueryDTO;
import com.yanxibao.mapper.HistoryMapper;
import com.yanxibao.mapper.UserinfoMapper;
import com.yanxibao.service.HistoryService;
import com.yanxibao.util.QueryUtil;
import com.yanxibao.util.UserHolder;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

import static com.yanxibao.util.WechatPatterns.TEST_ID;

/**
 * 历史;(_history)表服务实现类
 *
 * @author kongke
 * @date 2023/11/16
 */
@Service
public class HistoryServiceImpl extends ServiceImpl<HistoryMapper, History> implements HistoryService {

    @Resource
    private HistoryMapper historyMapper;

    @Resource
    private UserinfoMapper userinfoMapper;

    /**
     * 通过ID查询单条数据
     *
     * @param historyId 主键
     * @return 实例对象
     */
    @Override
    public Result<History> queryById(Integer historyId) {
        History history = getById(historyId);

        return history != null ? Result.success(history) : Result.error("05000", "未查询到数据");
    }


    /**
     * 分页查询
     *
     * @param history 筛选条件
     * @param current 当前页码
     * @param size    每页大小
     * @return
     */
    @Override
    public Result<PageQueryDTO<History>> pageQuery(History history, Integer current, Integer size) {

        Page<History> page = Page.of(current, size);

        @SuppressWarnings("unchecked")
        PageQueryDTO<History> dto = (PageQueryDTO<History>) QueryUtil.FltQuery("eq", history, page, historyMapper, null);

        return Result.success(dto);
    }


    /**
     * 新增数据
     *
     * @param history 实例对象
     * @return 实例对象
     */
    @Override
    public Result<History> insert(History history) {


        if (history.getHistoryId() != null) {
            return Result.error("05020", "请勿添加ID信息");
        }
        boolean save = save(history);

//        更新用户历史数
        userinfoMapper.addHis(history.getUserId());

        return save ? Result.success(history) : Result.error("05021", "新增数据失败");
    }

    /**
     * 更新数据
     *
     * @param history 实例对象
     * @return 实例对象
     */
    @Override
    public Result<History> update(History history) {
        boolean update = updateById(history);
        return update ? Result.success(history) : Result.error("05031", "更新数据失败");
    }

    /**
     * 通过主键删除数据
     *
     * @return 是否成功
     */
    @Override
    public Result<Boolean> deleteById(Integer historyId) {
//        String userId = UserHolder.getUser().getUserId();
//        测试
        String userId = TEST_ID;
        Integer del = historyMapper.delById(historyId, userId);

        return del > 1 ? Result.success(true) : Result.error("05040", "删除数据失败");
    }


}